<template>
  <div id="materInventory">
    <div class="makeHeader">
      <el-row
        type="flex"
        justify="space-between"
        align="center"
        :gutter="20"
        style="width: 100%; margin-bottom: 10px"
      >
        <el-col :span="6" style="display: flex">
          <span style="width: 100px; height: 40px; line-height: 40px">物料名称：</span>
          <el-cascader
            :props="props"
            v-model="from.typeId"
            :options="materialOptions"
            placeholder="物料名称"
            style="width: 100%"
            clearable
          ></el-cascader
        ></el-col>
        <el-col :span="10" style="display: flex">
          <span style="width: 100px; height: 40px; line-height: 40px">仓库名称：</span>

          <el-select v-model="from.storeId" placeholder="仓库名称" @change="change">
            <el-option
              v-for="item in storeOptions"
              :key="item.id"
              :label="item.storeName"
              :value="item.id"
            ></el-option> </el-select
        ></el-col>

        <el-col :span="7" style="display: flex"></el-col>
      </el-row>
      <el-row
        type="flex"
        justify="space-between"
        align="center"
        style="width: 100%; margin-bottom: 10px"
      >
        <el-col :span="2" style="display: flex">
          <el-button type="primary" @click="searchHandler">刷新</el-button>
          <el-button type="warning" @click="exportHandler">批量导出</el-button>
          <el-button type="primary" @click="editDialogStatusSet">阈值设置</el-button>
        </el-col>

        <el-col :span="7" style="text-align: right; float: right"
          ><el-button type="primary" @click="getProjectListApi">查询</el-button
          ><el-button plain @click="resetHandler">重置</el-button></el-col
        >
      </el-row>
    </div>
    <el-row class="contentDiv">
      <el-table
        :data="renderData"
        style="width: 100%"
        :header-cell-style="{ background: '#606266', color: '#fff' }"
        height="720"
        @selection-change="handleSelectionChange"
        lazy
        :key="key"
        v-loading="listLoading"
        :load="loadChild"
        row-key="id"
        :expand-row-keys="expandRowKeys"
        :tree-props="{ hasChildren: 'isParent' }"
      >
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-table
              :data="scope.row.detailList"
              style="width: 90%; max-height: 300px; margin: 0 auto"
              :header-cell-style="{
                'text-align': 'center',
                background: '#6062668c !important',
              }"
              :key="scope.$index"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
            >
              <el-table-column
                prop="typeName"
                label="物料名称"
                align="center"
                width="200"
              >
              </el-table-column>
              <el-table-column prop="supplierName" label="供应商" align="center">
              </el-table-column>
              <el-table-column prop="batchNum" label="批号" align="center">
              </el-table-column>
              <el-table-column prop="model" label="规格型号" align="center">
              </el-table-column>
              <el-table-column prop="unit" label="单位" align="center"> </el-table-column>

              <el-table-column prop="totalStorage" label="入库数量" align="center">
                <template slot-scope="tu">
                  <span>{{ tu.row.totalStorage | numberToCurrency }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="totalOut" label="累计出库" align="center">
                <template slot-scope="tu">
                  <span>{{ tu.row.totalOut | numberToCurrency }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="leaveNum" label="实时库存" align="center">
                <template slot-scope="tu">
                  <el-input
                    v-if="tu.row.isTrue"
                    v-model="tu.row.leaveNum"
                    @input="tu.row.leaveNum = Number(tu.row.leaveNum)"
                    type="number"
                  ></el-input>
                  <span v-else>{{ tu.row.leaveNum | numberToCurrency }}</span>
                </template>
              </el-table-column>

              <el-table-column label="操作" width="180" align="center">
                <template slot-scope="tu">
                  <el-button
                    v-if="!tu.row.isTrue"
                    plain
                    @click="editHandler(tu.row, scope.row, tu)"
                    >编辑</el-button
                  >
                  <el-button
                    v-else-if="tu.row.isTrue"
                    plain
                    @click="submitProjectApi(tu.row, scope.row)"
                    >提交</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column type="index" label="序号" width="100" align="center" />
        <el-table-column
          prop="storeName"
          label="仓库名称"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="typeName"
          label="物料名称"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="model"
          label="规格型号"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="unit"
          label="单位"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="totalStorage"
          label="累计入库"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.totalStorage | numberToCurrency }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalOut"
          label="累计出库"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.totalOut | numberToCurrency }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="lowerLimit"
          label="库存下限"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.lowerLimit | numberToCurrency }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="upperLimit"
          label="库存上限"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.upperLimit | numberToCurrency }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="leaveNum"
          label="实时库存"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.leaveNum | numberToCurrency }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="状态"
          width="180"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-button
              v-if="!scope.row.warning"
              type="text"
              class="text-success circleSpan"
              style="color: #67c23a"
              >正常</el-button
            >
            <el-button
              v-if="scope.row.warning"
              type="text"
              class="text-danger circleSpan"
              style="color: #f56c6c"
              >预警</el-button
            >

            <!-- <span v-else-if="!scope.row.warning" class="text-danger circleSpan"
              ></span
            > -->
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="footerDiv mt-10" style="text-align: right">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-row>
    <!-- 编辑 -->
    <el-dialog
      title="阈值设置"
      :visible.sync="editDialogStatus"
      width="30%"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      @closed="closededitDialogStatus"
    >
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px">
        <el-form-item label="物料名称" prop="typeId">
          <el-cascader
            :props="props"
            v-model="editForm.typeId"
            :options="materialOptions"
            placeholder="物料名称"
            style="width: 100%"
            clearable
            @change="materialChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="仓库名称" prop="storeId">
          <el-select
            style="width: 100%"
            v-model="editForm.storeId"
            placeholder="请选择仓库"
            @change="getThresholdApi"
          >
            <el-option
              v-for="item in storeOptions"
              :key="item.id"
              :label="item.storeName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格型号" prop="materialId">
          <el-select
            v-model="editForm.materialId"
            placeholder="请选择规格型号"
            @change="getThresholdApi"
            value-key="id"
            style="width: 100%"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.model"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库存上限" prop="upperLimit">
          <el-input
            v-model="editForm.upperLimit"
            @input="editForm.upperLimit = Number(editForm.upperLimit)"
            type="number"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="库存下限" prop="lowerLimit">
          <el-input
            v-model="editForm.lowerLimit"
            @input="editForm.lowerLimit = Number(editForm.lowerLimit)"
            type="number"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogStatus = false">取 消</el-button>
        <el-button type="primary" @click="editSaveHandler('editForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getMaterialInfoByTypeId } from "/src/http/backstageManage/materialDispatch/materialTypeMg.js";
import {
  stockByPage,
  getStockVoByTypeId,
  getStockExport,
  getThreshold,
  saveThreshold,
  updateThreshold,
  inventory,
} from "/src/http/materialDispatch/materInventory.js";
import { getMaterialTree } from "/src/http/materialDispatch/materPurchase.js";
import { getStoreList } from "/src/http/backstageManage/materialDispatch/warehouseMg.js";
import download from "/src/utils/downLoad.js";
export default {
  data() {
    return {
      listLoading: true,
      props: { value: "id", label: "name" },
      projectInput: "",
      renderData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      isSearch: false,
      multipleSelection: [],
      key: 1,
      maps: new Map(),
      expandRowKeys: [],

      // edit
      editTiele: "",
      editDialogStatus: false,
      from: {
        typeId: null,
        storeId: null,
      },
      editForm: {
        storeId: null,
        materialId: null,
        typeId: null,
        upperLimit: null,
        lowerLimit: null,
      },
      materialOptions: [], //物料树
      storeOptions: [], //仓库选择

      typeOptions: [],
      rules: {
        typeId: [{ required: true, message: "请输入出库名称", trigger: "blur" }],
        storeId: [{ required: true, message: "请选择分部分项", trigger: "blur" }],
        upperLimit: [
          { required: true, message: "请输入库存上限", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value > 99999) {
                callback(new Error("上限不能超过99999"));
              } else if (value < this.editForm.lowerLimit) {
                callback(new Error("上限不能低于下限"));
              } else if (value < 0) {
                callback(new Error("上限不能小于0"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        lowerLimit: [
          { required: true, message: "请输入库存下限", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                callback(new Error("下限不能小于0"));
              } else if (value > this.editForm.upperLimit) {
                callback(new Error("下限不能超过上限"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        materialId: [{ required: true, message: "请选择规格型号", trigger: "blur" }],
      },
    };
  },

  mounted() {
    this.getMaterialTreeApi();
    this.getStoreListApi();
    // setTimeout(() => {
    //   if (this.$route.query.storeId) {
    //     this.from.storeId = ~~JSON.parse(JSON.stringify(this.$route.query.storeId));
    //   }
    // }, 200);
    this.getProjectListApi();
  },

  methods: {
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 获取物料树
    getMaterialTreeApi() {
      getMaterialTree().then((res) => {
        if (res.code == 200) {
          this.materialOptions = res.data;
        }
      });
    },
    // 获取仓库
    getStoreListApi() {
      getStoreList().then((res) => {
        if (res.code == 200) {
          this.storeOptions = res.data;
        }
      });
    },
    async loadChild(tree, treeNode, resolve) {
      console.log(tree, treeNode, resolve);
      let _this = this;
      const pid = tree.brandNo; //取出当前的编码
      _this.maps.set(pid, { tree, treeNode, resolve }); //将当前选中节点数据存储到maps中
      get_brands_all({
        parentNo: pid,
        brandNo: "",
        brandName: "",
      }).then((res) => {
        if (res.results.length) {
          resolve(res.results);
        } else {
          resolve([]);
        }
      });
    },

    // 搜索
    searchHandler() {
      this.$router.go(0);
    },
    // 批量导出
    exportHandler() {
      if (this.multipleSelection.length === 0) {
        let obj = {
          storeId: this.from.storeId,
        };
        if (this.from.typeId) {
          obj.typeId = this.from.typeId[this.from.typeId.length - 1];
        }
        this.getRequirePlanExportApi(obj);
      } else {
        let exportIdList = this.multipleSelection.map((el) => {
          return el.id;
        });
        this.getRequirePlanExportApi({ exportIdList: exportIdList.join(",") });
      }
    },
    editDialogStatusSet() {
      if (this.multipleSelection.length > 1) {
        this.$message({
          message: "阈值设置不能选择多条",
          type: "warning",
        });
      } else if (this.multipleSelection.length == 1) {
        console.log(this.multipleSelection[0]);
        this.editForm.storeId = this.multipleSelection[0].storeId;
        let typeId = (
          this.multipleSelection[0].typeParentIds +
          "," +
          ~~this.multipleSelection[0].typeId
        ).split(",");
        this.editForm.typeId = typeId.map((element) => {
          return ~~element;
        });
        this.editForm.typeId.splice(0, 1);
        this.editForm.upperLimit = this.multipleSelection[0].upperLimit;
        this.editForm.lowerLimit = this.multipleSelection[0].lowerLimit;
        this.getStockVoByTypeIdApi(this.multipleSelection[0].typeId);
        this.editForm.materialId = this.multipleSelection[0].materialId;

        this.editDialogStatus = true;
        this.isSearch = this.multipleSelection[0].id;
        console.log(this.editForm);
      } else {
        this.editDialogStatus = true;
      }
    },
    getRequirePlanExportApi(obj) {
      let loading = this.$loading({
        lock: true,
        text: "导出中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      getStockExport(obj).then((res) => {
        download.excel(res, `物资库存${Date.now()}.xlsx`);
        loading.close();
      });
    },
    // 物料树选择
    materialChange() {
      this.getStockVoByTypeIdApi(this.editForm.typeId[this.editForm.typeId.length - 1]);
    },
    async getStockVoByTypeIdApi(id) {
      this.typeOptions = [];
      this.isSearch = null;
      this.editForm.materialId = null;
      getMaterialInfoByTypeId({
        id: id,
      }).then((res) => {
        if (res.code == 200) {
          this.typeOptions = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    storeChange(i) {
      if (this.editForm.materialId && this.editForm.storeId && this.editForm.typeId) {
        let params = {
          materialId: this.editForm.materialId,
          storeId: this.editForm.storeId,
          typeId: this.editForm.typeId[this.editForm.typeId.length - 1],
        };
        getThreshold(params).then((res) => {
          if (res.code == 200) {
            if (res.data) {
              this.isSearch = res.data.id;
              this.editForm.lowerLimit = res.data.lowerLimit;
              this.editForm.upperLimit = res.data.upperLimit;
            } else {
              this.isSearch = null;
              this.editForm.lowerLimit = null;
              this.editForm.upperLimit = null;
            }
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    getThresholdApi(v) {
      if (this.editForm.materialId && this.editForm.storeId && this.editForm.typeId) {
        let params = {
          materialId: this.editForm.materialId,
          storeId: this.editForm.storeId,
          typeId: this.editForm.typeId[this.editForm.typeId.length - 1],
        };
        getThreshold(params).then((res) => {
          if (res.code == 200) {
            if (res.data) {
              this.isSearch = res.data.id;
              this.editForm.lowerLimit = res.data.lowerLimit;
              this.editForm.upperLimit = res.data.upperLimit;
            } else {
              this.isSearch = null;
              this.editForm.lowerLimit = null;
              this.editForm.upperLimit = null;
            }
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    closededitDialogStatus() {
      this.typeOptions = [];
      this.editForm = {
        storeId: null,
        materialId: null,
        typeId: null,
        upperLimit: null,
        lowerLimit: null,
      };
      this.$refs["editForm"].resetFields();
    },
    // 重置
    resetHandler() {
      this.from = {
        typeId: null,
        storeId: null,
      };
      this.getProjectListApi();
    },
    shuaxin() {
      this.getProjectListApi();
    },
    // 新增
    addHandler() {
      this.editTiele = "新增";
      this.editDialogStatus = true;
    },
    //   编辑
    editHandler(v, data, number) {
      console.log(number);
      v.isTrue = true;
      this.expandRowKeys = [];
      this.$nextTick(() => {
        this.key++;
        this.expandRowKeys.push(data.id);
      });
      console.log(this.expandRowKeys);
      console.log(v);
      console.log(this.renderData);
    },
    submitProjectApi(v, data) {
      if (v.leaveNum < 0) {
        this.$message.error("实时库存不能为负数");
        return;
      }
      if (v.leaveNum > 100000) {
        this.$message.error("实时库存不能超过十万");
        return;
      }
      let params = {
        id: v.id,
        stockId: v.stockId,
        storageId: v.storageId,
        materialId: v.materialId,
        totalStorage: v.totalStorage,
        totalOut: v.totalOut,
        leaveNum: v.leaveNum,
      };
      console.log(params);
      this.listLoading = true;
      inventory(params).then((res) => {
        if (res.code == 200) {
          v.isTrue = false;
          this.expandRowKeys = [];
          this.$nextTick(() => {
            this.key++;
            this.expandRowKeys.push(data.id);
          });
          setTimeout(() => {
            this.listLoading = false;
            this.getProjectListApi();
          }, 500);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 每页几条
    handleSizeChange(v) {
      this.pageSize = v;
      this.currentPage = 1;

      this.getProjectListApi();
    },
    // 分页
    handleCurrentChange(v) {
      this.currentPage = v;
      this.getProjectListApi();
    },
    // editDialog保存
    editSaveHandler(formName) {
      // if (this.editTiele == "新增") {

      // } else {
      // this.updateProjectApi(params);
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.editForm));

          params.typeId = params.typeId[params.typeId.length - 1];
          if (this.isSearch) {
            this.updateThresholdApi(params);
          } else {
            this.saveThresholdApi(params);
          }
        } else {
          this.$message.error(res.message);
        }
      });
    },

    /**接口 */
    // 查询项目列表
    getProjectListApi() {
      let params = JSON.parse(JSON.stringify(this.from));

      if (params.typeId instanceof Array) {
        if (params.typeId) {
          params.typeId = params.typeId[params.typeId.length - 1];
        }
      }
      params.pageNum = this.currentPage;
      params.pageSize = this.pageSize;
      stockByPage(params).then((res) => {
        if (res.code == 200) {
          this.renderData = res.data.records;
          setTimeout(() => {
            this.listLoading = false;
          }, 500);
          this.renderData.forEach((item) => {
            if (item.detailList) {
              item.detailList.forEach((i) => {
                i.isTrue = false;
              });
            }
          });
          console.log(this.renderData);
          this.total = res.data.total;
          this.pageSize = res.data.size;
        }
      });
    },
    // 项目详情
    projectDetailApi(params) {
      console.log(params);
      //   projectDetail(params).then((res) => {
      //     console.log("res::: ", res);
      //   });
    },
    // 新增
    saveThresholdApi(params) {
      saveThreshold(params).then((res) => {
        if (res.code == 200) {
          this.currentPage = 1;
          this.from.typeId = params.typeId;
          this.from.storeId = params.storeId;
          this.getProjectListApi();
          this.$message.success("新增成功");
          this.editDialogStatus = false;
        } else {
          this.$message.error("新增失败");
        }
      });
    },
    // 编辑
    updateThresholdApi(params) {
      params.id = this.isSearch;
      updateThreshold(params).then((res) => {
        if (res.code == 200) {
          this.editDialogStatus = false;
          this.getProjectListApi(this.currentPage, this.pageSize);
          this.$message.success("编辑成功");
        } else {
          this.$message.error(res.message);
        }
      });
    },
    change() {
      this.$forceUpdate();
    },
  },
};
</script>

<style lang="less" scoped>
#materInventory {
  width: 100%;
  margin: 0 auto;
}
.el-date-editor {
  margin: 0 10px;
}
.imgBox {
  position: relative;
  top: 0;
  left: 0;
  .uploadImg {
    position: absolute;
    top: 30%;
    left: 30%;
    visibility: hidden;
  }
}
.imgBox:hover .uploadImg {
  visibility: visible;
}
:deep(.el-dialog__header) {
  background-color: rgb(43, 43, 53);
}
:deep(.el-dialog__title) {
  color: #fff;
}
// 图片上传
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.pDiv {
  background-color: #f5f7fa;
  color: #909399;
  border: 1px solid #dcdfe6;
  border-right: 0px;
  border-radius: 4px 0 0 4px;
  text-align: center;
  height: 40px;
  line-height: 40px;
  width: 13.7%;
}
:deep(.pSelect) {
  .el-input__inner {
    border-radius: 0 4px 4px 0;
    width: 107.5%;
  }
  .el-input__suffix {
    right: -5%;
  }
}
.mgb-10 {
  margin-bottom: 10px;
}
</style>
